# encoding: utf-8
import logging
import os
import time

from selenium.webdriver.chrome.options import Options
from seleniumwire import webdriver

def get_logger():
    logger = logging.getLogger('test')
    logger.setLevel(level=logging.DEBUG)

    formatter = logging.Formatter('%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s')

    file_handler = logging.FileHandler('taptap_comment_monitor.log')
    file_handler.setLevel(level=logging.INFO)
    file_handler.setFormatter(formatter)

    stream_handler = logging.StreamHandler()
    stream_handler.setLevel(logging.DEBUG)
    stream_handler.setFormatter(formatter)

    logger.addHandler(file_handler)
    logger.addHandler(stream_handler)
    return logger


logger = get_logger()

def create_chrome_driver_linux(proxy=""):
    try:
        chromedriver = f"/usr/local/bin/chromedriver"  # 这里写本地的chromedriver 的所在路径

        os.environ["webdriver.Chrome.driver"] = chromedriver  # 调用chrome浏览器
        options = Options()

        options.add_experimental_option("excludeSwitches", ["enable-automation", "enable-logging"])
        options.add_experimental_option("useAutomationExtension", False)
        options.add_argument("--disable-blink-features")
        options.add_argument("--disable-blink-features=AutomationControlled")


        options.add_argument(
            "user-agent=Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36")

        if proxy != "":
            options.add_argument(f'--proxy-server={proxy}')

        driver = webdriver.Chrome(chrome_options=options)
        script = 'Object.defineProperty(navigator,"webdriver",{get:() => false,});'
        driver.execute_script(script=script)

        driver.get('https://www.baidu.com/')
        title = driver.title
        if "百度" in title:
            print("create driver success!!!")
            return driver
        # else:
        #     refresh_num = 1
        #     while refresh_num <= 3:
        #         driver.refresh()
        #         time.sleep(2)
        #         title = driver.title
        #         if "百度" in title:
        #             return driver
        #         refresh_num += 1
        #     logger.info(f"wrong proxy detect result: {driver.page_source}")
        #     logger.info("create driver failed!!! ")
        #     return None

    except Exception as err:
        logger.exception(err)
        return None



if __name__ == "__main__":

    driver = create_chrome_driver_linux()